package com.thinkingcoder.tccache.core.operator;

import java.util.Arrays;
import java.util.Objects;

import com.thinkingcoder.tccache.core.model.CacheEntry;

/**
 * common operator.
 */
public class CommonOperator extends AbstractOperator {

    public int exists(String... keys) {
        return (keys == null) ? 0 : (int)Arrays.stream(keys).map(getMap()::containsKey).filter(x -> x).count();
    }

    public int del(String... keys) {
        return (keys == null) ? 0 : (int)Arrays.stream(keys).map(getMap()::remove).filter(Objects::nonNull).count();
    }

    public boolean expire(String key, long timeToLive) {
        CacheEntry<?> cacheEntry = getCacheEntry(key);
        if (cacheEntry == null) {
            return false;
        }
        cacheEntry.setTimeToLive(timeToLive);
        cacheEntry.setTimestamp(System.currentTimeMillis());
        return true;
    }

    public long timeToLive(String key) {
        CacheEntry<?> cacheEntry = getCacheEntry(key);
        if (cacheEntry == null) {
            return -2;
        }
        if (cacheEntry.getTimeToLive() == -1000L) {
            return -1;
        }

        long ret = (cacheEntry.getTimestamp() + cacheEntry.getTimeToLive() - CURRENT) / 1000;
        if (ret > 0) {
            return ret;
        }
        return -1;
    }

}
